import {
  Injectable,
  HttpException,
  ConflictException,
  BadGatewayException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RegionEntity } from './region.entity';
import { Repository } from 'typeorm';
import { RegionInsertDto } from './dto/region.insert.dto';
import { RegionSearchDto } from './dto/region.search.dto';
import { ResultListDto } from '../common/dto/result.list.dto';

@Injectable()
export class RegionService {
  constructor(
    @InjectRepository(RegionEntity)
    private readonly regionRepository: Repository<RegionEntity>,
  ) {}

  // 查询所有
  async findAll(): Promise<RegionEntity[]> {
    try {
      const find: RegionEntity[] = await this.regionRepository.find();
      if (!find) {
        throw new HttpException({ message: '查询地区代码失败' }, 502);
      }
      return find;
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }

  /**
   * 分页模糊查询
   * @param {object} [data] - 含有列表和总条数的对象返回值
   * @function [list] - typeorm的模糊查询+统计
   * @description 模糊查询对象需要是字符串
   */
  async pagination(body: RegionSearchDto): Promise<ResultListDto> {
    const data: ResultListDto = {
      list: [],
      total: 0,
    };
    try {
      const list = await this.regionRepository
        .createQueryBuilder('region')
        .where('region.id like :id')
        .andWhere('region.code like :code')
        .andWhere('region.name like :name')
        .andWhere('region.city_code like :city_code')
        .andWhere('region.level like :level')
        .andWhere('region.parent_id like :parent_id')
        .setParameters({
          // id
          id: `%${body.id ? body.id : ''}%`,
          // 代码
          code: `%${body.code ? body.code : ''}%`,
          // 名称
          name: `%${body.name ? body.name : ''}%`,
          // 城市代码
          city_code: `%${body.city_code ? body.city_code : ''}%`,
          // 地区级别
          level: `%${body.level ? body.level : ''}%`,
          // 父id
          parent_id: `%${body.parent_id ? body.parent_id : ''}%`,
        })
        .skip((body.page - 1) * body.limit)
        .take(body.limit)
        .getManyAndCount();
      data.list = list[0];
      data.total = list[1];
      return data;
    } catch (error) {
      throw new HttpException('获取列表失败', 502);
    }
  }

  // 新增
  async save(data: RegionInsertDto): Promise<boolean> {
    try {
      // 验证账号是否存在
      const findOneByAccount = await this.regionRepository.findOneBy({
        name: data.name,
        code: data.code,
      });
      if (findOneByAccount) {
        throw new ConflictException('账号已存在');
      }
      // 保存用户信息
      const save: RegionEntity = await this.regionRepository.save(data);
      if (!save) {
        throw new BadGatewayException('入库失败');
      }
      return true;
    } catch (error) {
      throw new HttpException(error.response, error.status);
    }
  }
}
